package com.taikang.hmp.hservice.paper.action.view;

import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.taikang.hmp.hservice.doctor.chineseevalmodel.bean.Hdbzdcchmedicine;
import com.taikang.hmp.hservice.paper.service.IQuestionnaireService;
import com.taikang.hmp.frame.common.ErrorConstant;
import com.taikang.hmp.frame.common.TKException;
import com.taikang.hmp.frame.common.datastructre.Dto;
import com.taikang.hmp.frame.common.datastructre.support.BaseDto;
import com.taikang.hmp.frame.common.datastructre.support.ResponseDto;
import com.taikang.hmp.frame.common.properties.PropertiesHelper;
import com.taikang.hmp.frame.common.web.action.BaseAction;

public class QuestionnaireAction extends BaseAction {

	private static final long serialVersionUID = 1L;

	private static Logger logger = LoggerFactory
			.getLogger(QuestionnaireAction.class);

	private IQuestionnaireService iquestionnaireService;

	@Override
	public String executeAction() {
		if ("getQuestion".equals(requestDto.getMethod())) {
			return getQuestion();
		} else if ("saveQuestionrResult".equals(requestDto.getMethod())) {
			return saveQuestionrResult();
		} else if ("getQuestionrResult".equals(requestDto.getMethod())) {
			return getQuestionrResult();
		} else if ("getJqys".equals(requestDto.getMethod())) {
			return getJqys();
		} else if ("getCorporeitySolar".equals(requestDto.getMethod())) {
			// "--【节气养生中获取节气和体质】: method getCorporeitySolar --"
			return getCorporeitySolar();
		}  else if ("getUid".equals(requestDto.getMethod())) {
			return getUid();
		} else {
			throw new TKException("no support method:" + requestDto.getMethod());
		}
	}

	/**
	 * 节气养生中获取节气和体质
	 * 
	 * @return
	 */
	private String getCorporeitySolar() {
		ResponseDto responseDto = new ResponseDto();
		Dto paramDto = null;
		paramDto = super.appendRequestBase(paramDto, requestDto);
		Dto resultList = iquestionnaireService.getCorporeitySolar(paramDto);
		if (!resultList.containsKey("corporeity")) {
			responseDto.addErrorCode(ErrorConstant.HD_NOT_TEST);
			super.setDataMap(responseDto);
			return SUCCESS;
		}
		Dto resultDto = new BaseDto();
		resultDto.put("resultlist", resultList);
		responseDto.pushResultDto(resultDto);
		super.setDataMap(responseDto);
		return SUCCESS;
	}

	public final String saveQuestionrResult() {
		ResponseDto responseDto = new ResponseDto();
		Dto paramDtos = requestDto.getRequestlist().get(0);
		String templateId = paramDtos.getAsString("templateid");
		Dto paramDto = null;
		List<Dto> list = paramDtos.getAsList("requestlist");
		paramDto = super.appendRequestBase(paramDto, requestDto);
		paramDto.put("requestlist", JSONArray.fromObject(list));
		paramDto.put("templateid", templateId);
		List<Dto> resultList = iquestionnaireService
				.saveQuestionrResult(paramDto);
		Dto resultDto = new BaseDto();
		resultDto.put("resultlist", resultList);
		responseDto.pushResultDto(resultDto);
		super.setDataMap(responseDto);
		return SUCCESS;
	}

	public final String getQuestion() {
		try {
			ResponseDto responseDto = new ResponseDto();
			// 获取参数
			Dto paramDto = null;
			if (requestDto.getRequestlist() != null
					&& !requestDto.getRequestlist().isEmpty()) {
				paramDto = requestDto.getRequestlist().get(0);
			}
			paramDto = super.appendRequestBase(paramDto, requestDto);
			logger.info("templateid: " + paramDto.getAsString("templateid"));
			List<Dto> resultList = iquestionnaireService.getQuestion(paramDto
					.getAsString("templateid"));
			Dto resultDto = new BaseDto();
			resultDto.put("resultlist", resultList);
			responseDto.pushResultDto(resultDto);
			super.setDataMap(responseDto);
			return SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			dataMap.put("errorInfo", "获取问卷失败");
			dataMap.put("success", false);
			return SUCCESS;
		}
	}

	public final String getQuestionrResult() {

		try {
			ResponseDto responseDto = new ResponseDto();
			Dto paramDto = null;
			if (requestDto.getRequestlist() != null
					&& !requestDto.getRequestlist().isEmpty()) {
				paramDto = requestDto.getRequestlist().get(0);
			}
			paramDto = super.appendRequestBase(paramDto, requestDto);
			List<Dto> resultList = iquestionnaireService
					.getQuestionrResult(paramDto);
			Dto resultDto = new BaseDto();
			resultDto.put("resultlist", resultList);
			responseDto.pushResultDto(resultDto);
			super.setDataMap(responseDto);
			return SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			dataMap.put("errorInfo", "获取问卷结果失败");
			dataMap.put("success", false);
			return SUCCESS;
		}

	}

	public String getJqys() {
		ResponseDto responseDto = new ResponseDto();
		Dto paramDto = requestDto.getRequestlist().get(0);
		paramDto = super.appendRequestBase(paramDto, requestDto);
		Hdbzdcchmedicine sdf = iquestionnaireService.getJqys(paramDto);
		Dto resultDto = new BaseDto();
		resultDto.put("sdf", sdf);
		responseDto.pushResultDto(resultDto);
		super.setDataMap(responseDto);
		return SUCCESS;

	}
	public String getUid() {
		ResponseDto responseDto = new ResponseDto();
		Dto paramDto = requestDto.getRequestlist().get(0);
		paramDto = super.appendRequestBase(paramDto, requestDto);
		String url = PropertiesHelper.appHelper.getValue("ThreeUrl")+"/api/oauth/token?grant_type=authorization_code&third_id=HEALTH_HD&code="+paramDto.getAsString("code");
		String result =  httpGet(url);
		JSONObject obj = JSONObject.fromObject(result);
		String url2 = PropertiesHelper.appHelper.getValue("ThreeUrl")+"/api/oauth/user?third_id=HEALTH_HD&access_token="+obj.getString("access_token");
		String result2 =  httpGet(url2);
		JSONObject obj2 = JSONObject.fromObject(result2);
		Dto resultDto = new BaseDto();
		resultDto.put("user_code", obj2.getString("user_code"));
		responseDto.pushResultDto(resultDto);
		super.setDataMap(responseDto);
		return SUCCESS;

	}

	public IQuestionnaireService getIquestionnaireService() {
		return iquestionnaireService;
	}

	public void setIquestionnaireService(
			IQuestionnaireService iquestionnaireService) {
		this.iquestionnaireService = iquestionnaireService;
	}

	 // 辅助函数: 使用 GET 方式发起一个 HTTP 请求, 并返回结果
    private static String httpGet(String url)
    {
    
         
        String response=new String();
        CloseableHttpClient client = HttpClients.createDefault();
       
        //使用POST方法
        HttpGet method = new HttpGet(url);  
       
        
        
        try{
       	 CloseableHttpResponse httpResponse =   client.execute(method);
       	 HttpEntity entity = httpResponse.getEntity();
            if (null != entity){
           	 
                if(httpResponse.getStatusLine().getStatusCode()==200)
                {
                    response = EntityUtils.toString(entity);
                }
            }
        }catch (Exception ex)
        {
           ex.printStackTrace();
        }

        
       
        //释放连接
        method.releaseConnection();
        // 转换编码
        //return Utility.utf8Togb2312(response);
        return response;
    }
}
